package controllers;

import helpers.StringHelper;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.TaggerModel;

import edu.stanford.nlp.tagger.maxent.MaxentTagger;

public class CreateTagServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		String content = (String) request.getParameter("content");
		
		String tags = "";
		
		if (content != null && !content.isEmpty()) { 
			TaggerModel tagger = TaggerModel.getInstance();
			tags = tagger.getTags(content);
			tags = getKeywords(tags);
		}
		
		response.getWriter().println(tags);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		String content = (String) request.getParameter("content");
		
		String tags = "";
		
		if (content != null && !content.isEmpty()) { 
			TaggerModel tagger = TaggerModel.getInstance();
			tags = tagger.getTags(content);
			tags = getKeywords(tags);
		}
		
		response.getWriter().println(tags);
	}
	
	private String getKeywords(String content) {
		String keywords = "";
		
		List<String> list = StringHelper.findString("[^_, ]+(_NNP)", content);
		list = removeDuplicates(list);
		keywords = StringHelper.listToString(list, ",");
		keywords = keywords.replace("_NNP", "");
		
		return keywords;
	}
	
	public static List removeDuplicates(List list) {
	        HashSet set = new HashSet(list);
	        list.clear();
	        list.addAll(set);
	        return list;
	}
	
	public static void main(String[] args) {
		String content = "Once_RB you_PRP write_VB the_DT code_NN ,_, Eclipse_NNP will_MD tell_VB you_PRP to_TO import_VB the_DT MaxentTagger_NNP and_CC inform_VB you_PRP that_IN it_PRP throws_VBZ some_DT exceptions_NNS ._. Use_NN eclipse_NN to_TO add_VB all_DT that_DT to_TO the_DT code_NN ._. ";
		
		System.out.println(StringHelper.listToString(StringHelper.findString("[^_, ]+(_NNP)", content), ","));
	}
}
